package com.wzapp.sitposture.task.endpoint;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wzapp.sitposture.common.annotation.NeedLogin;
import com.wzapp.sitposture.common.base.BaseEndpoint;
import com.wzapp.sitposture.common.base.HeaderParam;
import com.wzapp.sitposture.common.error.CustomizedException;
import com.wzapp.sitposture.common.restful.RestfulResult;
import com.wzapp.sitposture.common.util.ToolUtil;
import com.wzapp.sitposture.task.entity.Task;
import com.wzapp.sitposture.task.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by qianglong on 2018/1/22.
 */
@Slf4j
@RestController
public class TaskEndpoint extends BaseEndpoint{

    @Autowired
    TaskService taskService;


    private static int LIST_SIZE = 200;

    /**
     * 功能: 创建定时任务<br/>
     *
     * @author ql
     * @create 2018/1/24 11:56
     * @param task
     * @return org.springframework.http.ResponseEntity
     **/
    @NeedLogin
    @PostMapping("/task/tasks")
    public ResponseEntity createTasks(@RequestBody Task task, HttpSession session) throws CustomizedException {

        HeaderParam headerParam = getHeaderParam();
        String userId = headerParam.getUserId();
        String name = task.getName();
        JSONObject params = task.getParams();

        List<String> idsList = new ArrayList<>();
        if(ToolUtil.isNotEmpty(params)){
            JSONArray jsonArray = params.getJSONArray("ids");
            idsList = jsonArray.toJavaList(String.class);
        }

        task.setCreator(userId);

        Task other = taskService.findByCreatorAndName(userId,name);

        Task taskDB = null;
        if(other != null){
            if(ToolUtil.isNotEmpty(other.getParams())){
                List<String> idsOtherList = other.getParams().getJSONArray("ids").toJavaList(String.class);
                idsList.addAll(idsOtherList);
                Map map = new HashMap(1);
                map.put("ids",idsList);
                other.setParams(JSONObject.parseObject(JSONObject.toJSONString(map)));
            }
            taskDB = taskService.saveTask(other);
        }else{
            taskDB = taskService.saveTask(task);
        }

        return RestfulResult.createSuccess(taskDB);
    }

}
